package com.augmentum.oes.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.augmentum.oes.Constants;
import com.augmentum.oes.model.Exam;
import com.augmentum.oes.model.Pagination;
import com.augmentum.oes.model.User;
import com.augmentum.oes.service.ExamService;
import com.augmentum.oes.util.SessionUtil;

@Controller
@RequestMapping("/exam")
public class ExamController extends ExceptionHandle {
    @Autowired
    private ExamService examService;

    @RequestMapping("examPage")
    public String getPage() {
        return Constants.EXAM_PAGE;
    }

    @RequestMapping(value = "/examJson", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String examJson(Pagination<Exam> page) throws JsonGenerationException, JsonMappingException, IOException {
        List<Exam> list = examService.examList(page);
        page.setItemList(list);
        ObjectMapper om = new ObjectMapper();
        return om.writeValueAsString(page);
    }

    @RequestMapping("createPage")
    public String createE() {
        return Constants.EDIT_EXAM;
    }

    @RequestMapping("create")
    public String createExam(Exam exam, String date, String hour) throws ParseException {
        User user = (User) SessionUtil.getSession("user");
        int id = user.getUserId();
        examService.setInfo(exam, date, hour, id);
        examService.createExam(exam);
        SessionUtil.addSession("success", 1);
        return Constants.EXAM_ACTION;
    }

    @RequestMapping("getCount")
    @ResponseBody
    public int getCount(HttpServletResponse response) throws IOException {
        int count = examService.getQuestionCount();
        return count;
    }
}
